package com.shuimin.as;

import com.shuimin.as.model.sys.Rank;
import com.shuimin.as.model.sys.Shop;
import com.shuimin.as.model.sys.User;
import com.shuimin.as.service.sys.RankService;
import com.shuimin.as.service.sys.ShopService;
import com.shuimin.as.service.sys.SysRoles;
import com.shuimin.as.service.sys.UserService;
import pond.common.S;
import pond.common.STRING;
import pond.db.Record;
import pond.web.Render;
import pond.web.Request;
import pond.web.restful.API;

import java.io.IOException;
import java.util.List;

import static com.shuimin.as.util.RespUtil.success;


/**
 * Created by ed on 12/24/15.
 */
public class USER extends API {
  {
    get("/", (req, resp) -> {
      String uid = req.param("uid");
      if (STRING.isBlank(uid))
        resp.render(Render.json(App.DB.get(UserService::all)));
      else
        resp.render(Render.json(UserService.getUserByUidOrName(uid)));
    });

    get("/salesmen", (req, resp) -> {
      String shop_id = req.param("shop_id");
      resp.render(Render.json(App.DB.get(t -> UserService.salesmenForShop(shop_id,t))));
    });

    get("/evaluator", (req, resp) -> {
      String shop_id = req.param("shop_id");
      resp.render(Render.json(App.DB.get(t -> UserService.evaluator(shop_id,t))));
    });

    get("/:uid", (req, resp) -> {
      String uid = req.paramNonBlank("uid", "uid blank");
      resp.render(Render.json(UserService.getUserByUid(uid)));
    });

    post("/", (req, resp) -> {
//      req.paramNonBlank("shop_id")
//      if(STRING.isBlank(req.param("shop_id"))){
//        throw new EndToEndException(400, "请选择门店");
//      }
      req.paramNonBlank("uid", "uid 不能为空");
      req.paramNonBlank("name", "name 不能为空");
      User user = (User) Record.newEntity(User.class).merge(req.toMap());

      App.DB.post(t -> {

        UserService.addUser(user, t);
      });
      App.rbac.sync(UserService.briefForRole(), SysRoles.all);
      resp.status(201);
      resp.render(Render.json(user));
    });


    del("/:uid", (req, resp) -> {
      String uid = req.paramNonBlank("uid", "uid 不能为空");

      App.DB.post(t -> {
        UserService.delUser(UserService.getUserByUid(uid), t);
      });

      resp.send(201, uid);
    });

    put("/:uid", (req, resp) -> {
      String uid = req.paramNonBlank("uid", "uid 不能为空");

      String view_shops = req.param("_view_shops");
      String[] _view_shops = S.avoidNull(view_shops, "").split(",");

      App.DB.post(t -> {
        User old = UserService.getUserByUid(uid);
        S._assert(old);
        UserService.clearViewShops(old, t);
        UserService.addViewShops(old, _view_shops, t);
        old.merge(req.toMap());
        UserService.updUser(old, t);
      });
      App.rbac.sync(UserService.briefForRole(), SysRoles.all);
      resp.send(200, uid);
    });

    //TODO 和 通用查询合并
    /**
     * 查询出所有没有门店的用户
     */
    get("/shop/null", (req, resp) -> {
      resp.render(Render.json(UserService.getUserWithoutShop()));
    });

    post("/:uid/shop/", (req, resp) -> {
      String uid = req.param("uid");
      String shop_id = req.param("shop_id");
      Shop shop = ShopService.get(shop_id);
      User user = UserService.getUserByUid(uid);
      S._assertNotNull(shop, user);
      UserService.updShopForUser(user, shop);
      success(resp, "用户[" + user.get("name") + "]已加入门店[" + shop.get("name") + "]");
    });

    del("/:uid/shop/", (req, resp) -> {
      String uid = req.param("uid");
      User user = UserService.getUserByUid(uid);
      S._assertNotNull(user);
      UserService.delShopForUser(user);
      success(resp, "用户[" + user.get("name") + "]已退出门店");
    });

    get("/:id/ranks/", (req, resp) -> {
      String id = req.param("id");
      List<Rank> ranks = App.DB.get(t -> RankService.ranksForUser(t, id));
      resp.render(Render.json(ranks));
    });


    post("/:id/ranks/:rank_id", (req, resp) -> {

      String id = req.param("id");
      String rank_id = req.param("rank_id");
      App.DB.post(t -> RankService.addRankToUser(t, rank_id, id));
      resp.send(201);

    });

    del("/:id/ranks/:rank_id", (req, resp) -> {

      String id = req.param("id");
      String rank_id = req.param("rank_id");
      App.DB.post(t -> RankService.removeRankFromUser(t, rank_id, id));

      resp.send(204);
    });
    post("/import", (req, resp) -> {
      Request.UploadFile uf = req.file("user");
      List<User> list = null;
      try {
        list = User.analyze(uf.inputStream());
      } catch (IOException e) {
        e.printStackTrace();
      }
      final List<User> finalList = list;
      App.DB.post(t -> {
        S._for(finalList).each(item -> {
          item.setId(S.uuid.vid());
          t.recordInsert(item);
          String _rank = item.get("rank");
          if (STRING.notBlank(_rank)) {
            Rank rank = RankService.getByName(_rank, t);
            if (rank != null)
              RankService.addRankToUser(t, rank.id(), item.id());
          }
          String _shop = item.get("shop");
          if (STRING.notBlank(_shop)) {
            List<Shop> shops = ShopService.getByName(_shop);
            if (shops.size() == 1) item.set("shop_id", shops.get(0).id());
          }
        });
      });

      resp.send(200);
    });

  }



}
